<template>
    <div class="edit-warehouse-form">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="仓库名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入仓库名称"></el-input>
            </el-form-item>

            <el-form-item label="仓库位置" prop="location">
                <el-input v-model="form.location" placeholder="请输入仓库位置"></el-input>
            </el-form-item>

            <el-form-item label="创建人" prop="created_by">
                <el-input v-model="form.created_by" placeholder="请输入创建人 ID"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm">确认</el-button>
                <el-button @click="$emit('cancel')">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { updateWarehouse } from '@/api/warehouse'; // 假设更新仓库的 API

const props = defineProps({
    warehouseData: {
        type: Object,
        required: true
    }
});

const emit = defineEmits(['cancel', 'success']);

const formRef = ref(null);

const form = ref({
    id: props.warehouseData.id,
    name: '',
    location: '',
    created_by: ''
});

const rules = {
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
    location: [{ required: true, message: '请输入仓库位置', trigger: 'blur' }],
    created_by: [{ required: true, message: '请输入创建人 ID', trigger: 'blur' }]
};
// console.log(props.warehouseData);
const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const submitData = {
                    id : props.warehouseData.id,
                    name: form.value.name.trim(),
                    location: form.value.location.trim(),
                    created_by: parseInt(form.value.created_by, 10)
                };
                console.log("updateWarehouse",submitData);
                

                const { data } = await updateWarehouse(submitData);
                if (data.code === 200) {
                    ElMessage.success('更新成功');
                    emit('success');
                } else {
                    ElMessage.error(data.message || '更新失败');
                }
            } catch (error) {
                ElMessage.error('更新失败：' + error.message);
            }
        }
    });
};

onMounted(() => {
    // 初始化表单数据
    form.value = {
        name: props.warehouseData.name,
        location: props.warehouseData.location,
        created_by: props.warehouseData.created_by.toString()
    };
});
</script>

<style scoped>
.edit-warehouse-form {
    padding: 20px;
}
</style>